/*
package org.example.util;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.util.Matrix;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class SmallDeliveryNoteGenerator {

    // 纸张尺寸 (131mm × 72mm) 转换为点 (1mm = 2.83465点)
    private static final float PAGE_WIDTH = 131 * 2.83465f;
    private static final float PAGE_HEIGHT = 72 * 2.83465f;
    private static final PDRectangle PAGE_SIZE = new PDRectangle(PAGE_WIDTH, PAGE_HEIGHT);

    // 边距设置
    private static final float MARGIN = 10;
    private static final float LINE_HEIGHT = 12;
    private static final float TITLE_HEIGHT = 16;

    // 字体设置 - 使用支持中文的字体
    private static PDFont TITLE_FONT;
    private static PDFont HEADER_FONT;
    private static PDFont CONTENT_FONT;
    private static final float TITLE_FONT_SIZE = 10;
    private static final float HEADER_FONT_SIZE = 8;
    private static final float CONTENT_FONT_SIZE = 8;

    // 数据模型
    public static class DeliveryData {
        public String companyName = "卓越科技有限公司";
        public String logoPath = null; // 可选的公司logo路径
        public String orderNumber = "ORD-20250722-001";
        public String customerName = "张三";
        public String phone = "13800138000";
        public String address = "北京市海淀区科技园路88号创新大厦B座5层";
        public String deliveryDate = "2025-07-22";
        public String deliveryTime = "14:00-18:00";
        public String[] products = {
                "华为MateBook X Pro 2025款 13英寸",
                "苹果Magic Mouse 2代",
                "罗技K380蓝牙键盘"
        };
        public int[] quantities = {1, 1, 1};
        public double[] prices = {8999.00, 699.00, 249.00};
        public String notes = "请当面检查商品完好性，签收后视为认可商品质量";
    }

    public static void main(String[] args) {
        try {
            // 准备数据
            DeliveryData data = new DeliveryData();

            // 加载中文字体
            //loadChineseFonts();

            // 生成发货单
            generateDeliveryNote(data, "C:\\Users\\15711\\Desktop\\small_delivery_note.pdf");

            System.out.println("发货单生成成功！文件已保存为: small_delivery_note.pdf");
        } catch (IOException e) {
            System.err.println("生成发货单时出错: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("初始化错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void loadChineseFonts(PDDocument doc) throws IOException {
        String os = System.getProperty("os.name").toLowerCase();

        if (os.contains("win")) {
            TITLE_FONT = PDType0Font.load(doc, new File("C:\\Windows\\Fonts\\simhei.ttf"));
            HEADER_FONT = TITLE_FONT;
            CONTENT_FONT = TITLE_FONT;
        } else if (os.contains("mac")) {
            TITLE_FONT = PDType0Font.load(doc, new File("/System/Library/Fonts/PingFang.ttc"));
            HEADER_FONT = TITLE_FONT;
            CONTENT_FONT = TITLE_FONT;
        } else {
            // 尝试从资源加载
            InputStream isHei = SmallDeliveryNoteGenerator.class.getResourceAsStream("/fonts/SimHei.ttf");
            if (isHei != null) {
                TITLE_FONT = PDType0Font.load(doc, isHei);
                HEADER_FONT = TITLE_FONT;
                CONTENT_FONT = TITLE_FONT;
            }
        }

        // 如果加载失败，使用后备字体
        if (TITLE_FONT == null) {
            System.err.println("使用默认字体");
            */
/*TITLE_FONT = PDType1Font.HELVETICA_BOLD;
            HEADER_FONT = PDType1Font.HELVETICA_BOLD;
            CONTENT_FONT = PDType1Font.HELVETICA;*//*

        }
    }

    public static void generateDeliveryNote(DeliveryData data, String outputPath) throws IOException {
        try (PDDocument document = new PDDocument()) {
            loadChineseFonts(document);
            // 创建页面
            PDPage page = new PDPage(PAGE_SIZE);
            document.addPage(page);

            try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
                // 设置背景色（可选）
                drawBackground(contentStream);

                // 添加公司logo（如果有）
                if (data.logoPath != null) {
                    try {
                        PDImageXObject logo = PDImageXObject.createFromFile(data.logoPath, document);
                        float logoWidth = 30; // 缩小logo尺寸以适应小纸张
                        float logoHeight = logo.getHeight() * logoWidth / logo.getWidth();
                        float logoX = (PAGE_WIDTH - logoWidth) / 2;
                        float logoY = PAGE_HEIGHT - MARGIN - logoHeight;
                        contentStream.drawImage(logo, logoX, logoY, logoWidth, logoHeight);
                    } catch (IOException e) {
                        System.err.println("无法加载logo: " + e.getMessage());
                    }
                }

                // 添加标题
                drawCenteredText(contentStream, "发货单",
                        PAGE_HEIGHT - MARGIN - 20,
                        TITLE_FONT, TITLE_FONT_SIZE, Color.BLACK);

                // 添加订单信息
                float yPosition = PAGE_HEIGHT - MARGIN - 35; // 上移以适应小纸张
                yPosition = drawLabelValuePair(contentStream, "订单号:", data.orderNumber, yPosition);
                yPosition = drawLabelValuePair(contentStream, "客户:", data.customerName, yPosition);
                yPosition = drawLabelValuePair(contentStream, "电话:", data.phone, yPosition);
                yPosition = drawLabelValuePair(contentStream, "地址:", data.address, yPosition, 30);
                yPosition = drawLabelValuePair(contentStream, "配送日期:", data.deliveryDate, yPosition);
                yPosition = drawLabelValuePair(contentStream, "配送时段:", data.deliveryTime, yPosition);

                // 添加产品标题
                yPosition -= 8; // 减少间距
                drawSectionTitle(contentStream, "商品清单", yPosition);
                yPosition -= LINE_HEIGHT - 2; // 减少行高

                // 添加产品表格
                float tableY = yPosition - 3;
                float tableHeight = drawProductTable(contentStream, data, tableY);
                yPosition = tableY - tableHeight - 3;

                // 添加备注
                if (data.notes != null && !data.notes.isEmpty()) {
                    drawWrappedText(contentStream, "备注: " + data.notes,
                            MARGIN, yPosition,
                            PAGE_WIDTH - 2 * MARGIN,
                            CONTENT_FONT, CONTENT_FONT_SIZE - 1, Color.RED); // 减小字体
                }

                // 添加公司名称
                drawCenteredText(contentStream, data.companyName,
                        MARGIN + 3,
                        HEADER_FONT, HEADER_FONT_SIZE - 1, new Color(100, 100, 100)); // 减小字体
            }

            // 保存文档
            document.save(outputPath);
        }
    }

    private static void drawBackground(PDPageContentStream contentStream) throws IOException {
        contentStream.setNonStrokingColor(new Color(245, 245, 245));
        contentStream.addRect(0, 0, PAGE_WIDTH, PAGE_HEIGHT);
        contentStream.fill();

        // 添加边框
        contentStream.setStrokingColor(new Color(200, 200, 200));
        contentStream.setLineWidth(0.5f);
        contentStream.addRect(MARGIN, MARGIN, PAGE_WIDTH - 2*MARGIN, PAGE_HEIGHT - 2*MARGIN);
        contentStream.stroke();
    }

    private static float drawLabelValuePair(
            PDPageContentStream contentStream,
            String label, String value,
            float yPosition) throws IOException {
        return drawLabelValuePair(contentStream, label, value, yPosition, 0);
    }

    private static float drawLabelValuePair(
            PDPageContentStream contentStream,
            String label, String value,
            float yPosition, float maxWidth) throws IOException {

        contentStream.setFont(HEADER_FONT, HEADER_FONT_SIZE);
        contentStream.setNonStrokingColor(Color.BLACK);

        // 绘制标签
        contentStream.beginText();
        contentStream.newLineAtOffset(MARGIN, yPosition);
        contentStream.showText(label);
        contentStream.endText();

        // 绘制值
        contentStream.setFont(CONTENT_FONT, CONTENT_FONT_SIZE);

        float valueX = MARGIN + HEADER_FONT.getStringWidth(label) * HEADER_FONT_SIZE / 1000 + 3; // 减少间距
        float availableWidth = PAGE_WIDTH - valueX - MARGIN;

        if (maxWidth > 0 && maxWidth < availableWidth) {
            availableWidth = maxWidth;
        }

        // 如果值太长，自动换行
        if (CONTENT_FONT.getStringWidth(value) * CONTENT_FONT_SIZE / 1000 > availableWidth) {
            return drawWrappedText(contentStream, value, valueX, yPosition, availableWidth,
                    CONTENT_FONT, CONTENT_FONT_SIZE, Color.BLACK);
        } else {
            contentStream.beginText();
            contentStream.newLineAtOffset(valueX, yPosition);
            contentStream.showText(value);
            contentStream.endText();

            return yPosition - LINE_HEIGHT;
        }
    }

    private static void drawSectionTitle(
            PDPageContentStream contentStream,
            String title, float yPosition) throws IOException {

        contentStream.setFont(HEADER_FONT, HEADER_FONT_SIZE);
        contentStream.setNonStrokingColor(new Color(70, 130, 180)); // 钢蓝色

        contentStream.beginText();
        contentStream.newLineAtOffset(MARGIN, yPosition);
        contentStream.showText(title);
        contentStream.endText();

        // 添加下划线
        contentStream.setStrokingColor(new Color(70, 130, 180));
        contentStream.setLineWidth(0.5f); // 减细线宽
        contentStream.moveTo(MARGIN, yPosition - 2);
        contentStream.lineTo(MARGIN + HEADER_FONT.getStringWidth(title) * HEADER_FONT_SIZE / 1000, yPosition - 2);
        contentStream.stroke();
    }

    private static float drawProductTable(
            PDPageContentStream contentStream,
            DeliveryData data, float yPosition) throws IOException {

        float tableWidth = PAGE_WIDTH - 2 * MARGIN;
        float col1Width = tableWidth * 0.55f; // 调整列宽
        float col2Width = tableWidth * 0.15f;
        float col3Width = tableWidth * 0.30f;

        float startY = yPosition;
        float currentY = yPosition;

        // 表头
        contentStream.setFont(HEADER_FONT, HEADER_FONT_SIZE);
        contentStream.setNonStrokingColor(Color.BLACK);

        // 绘制表头背景
        contentStream.setNonStrokingColor(new Color(230, 230, 230));
        contentStream.addRect(MARGIN, currentY, tableWidth, -LINE_HEIGHT);
        contentStream.fill();

        // 绘制表头文本
        contentStream.setNonStrokingColor(Color.BLACK);
        contentStream.beginText();
        contentStream.newLineAtOffset(MARGIN + 2, currentY - 10);
        contentStream.showText("商品名称");
        contentStream.endText();

        contentStream.beginText();
        contentStream.newLineAtOffset(MARGIN + col1Width + 2, currentY - 10);
        contentStream.showText("数量");
        contentStream.endText();

        contentStream.beginText();
        contentStream.newLineAtOffset(MARGIN + col1Width + col2Width + 2, currentY - 10);
        contentStream.showText("金额");
        contentStream.endText();

        currentY -= LINE_HEIGHT;

        // 绘制表格线
        contentStream.setStrokingColor(new Color(180, 180, 180));
        contentStream.setLineWidth(0.2f); // 减细线宽

        // 表头下划线
        contentStream.moveTo(MARGIN, currentY);
        contentStream.lineTo(MARGIN + tableWidth, currentY);
        contentStream.stroke();

        // 列分隔线
        contentStream.moveTo(MARGIN + col1Width, yPosition);
        contentStream.lineTo(MARGIN + col1Width, currentY);
        contentStream.stroke();

        contentStream.moveTo(MARGIN + col1Width + col2Width, yPosition);
        contentStream.lineTo(MARGIN + col1Width + col2Width, currentY);
        contentStream.stroke();

        // 添加产品行
        contentStream.setFont(CONTENT_FONT, CONTENT_FONT_SIZE);
        double total = 0;

        for (int i = 0; i < data.products.length; i++) {
            currentY -= LINE_HEIGHT;

            // 商品名称（自动换行）
            String product = data.products[i];
            float maxWidth = col1Width - 4;

            // 绘制商品名称（自动换行）
            float textHeight = drawWrappedText(contentStream, product,
                    MARGIN + 2, currentY - 10,
                    maxWidth, CONTENT_FONT, CONTENT_FONT_SIZE, Color.BLACK);

            // 调整行高以适应多行文本
            if (textHeight > LINE_HEIGHT) {
                currentY -= (textHeight - LINE_HEIGHT);
            }

            // 数量
            String quantity = String.valueOf(data.quantities[i]);
            contentStream.beginText();
            contentStream.newLineAtOffset(MARGIN + col1Width + (col2Width - CONTENT_FONT.getStringWidth(quantity) * CONTENT_FONT_SIZE / 1000) / 2,
                    currentY - 10);
            contentStream.showText(quantity);
            contentStream.endText();

            // 金额
            double price = data.prices[i] * data.quantities[i];
            total += price;
            String priceStr = String.format("$%.2f", price);
            contentStream.beginText();
            contentStream.newLineAtOffset(MARGIN + col1Width + col2Width + (col3Width - CONTENT_FONT.getStringWidth(priceStr) * CONTENT_FONT_SIZE / 1000) / 2,
                    currentY - 10);
            contentStream.showText(priceStr);
            contentStream.endText();

            // 行分隔线
            contentStream.moveTo(MARGIN, currentY);
            contentStream.lineTo(MARGIN + tableWidth, currentY);
            contentStream.stroke();
        }

        // 总计行
        currentY -= LINE_HEIGHT;
        contentStream.setFont(HEADER_FONT, HEADER_FONT_SIZE);

        contentStream.beginText();
        contentStream.newLineAtOffset(MARGIN + 2, currentY - 10);
        contentStream.showText("总计");
        contentStream.endText();

        String totalStr = String.format("$%.2f", total);
        contentStream.beginText();
        contentStream.newLineAtOffset(MARGIN + col1Width + col2Width + (col3Width - HEADER_FONT.getStringWidth(totalStr) * HEADER_FONT_SIZE / 1000) / 2,
                currentY - 10);
        contentStream.showText(totalStr);
        contentStream.endText();

        // 表格底部边框
        contentStream.moveTo(MARGIN, currentY - LINE_HEIGHT);
        contentStream.lineTo(MARGIN + tableWidth, currentY - LINE_HEIGHT);
        contentStream.stroke();

        // 返回表格高度
        return startY - (currentY - LINE_HEIGHT);
    }

    private static void drawCenteredText(
            PDPageContentStream contentStream,
            String text, float y,
            PDFont font, float fontSize, Color color) throws IOException {

        contentStream.setFont(font, fontSize);
        contentStream.setNonStrokingColor(color);

        float textWidth = font.getStringWidth(text) * fontSize / 1000;
        float x = (PAGE_WIDTH - textWidth) / 2;

        contentStream.beginText();
        contentStream.newLineAtOffset(x, y);
        contentStream.showText(text);
        contentStream.endText();
    }

    private static float drawWrappedText(
            PDPageContentStream contentStream,
            String text, float x, float y,
            float maxWidth,
            PDFont font, float fontSize, Color color) throws IOException {

        contentStream.setFont(font, fontSize);
        contentStream.setNonStrokingColor(color);

        String[] words = text.split("\\s+");
        StringBuilder currentLine = new StringBuilder();
        float currentY = y;
        float lineHeight = fontSize * 1.2f;
        int lines = 0;

        for (String word : words) {
            String testLine = currentLine.length() == 0 ? word : currentLine + " " + word;
            float testWidth = font.getStringWidth(testLine) * fontSize / 1000;

            if (testWidth > maxWidth && currentLine.length() > 0) {
                // 绘制当前行
                contentStream.beginText();
                contentStream.newLineAtOffset(x, currentY);
                contentStream.showText(currentLine.toString());
                contentStream.endText();

                currentLine = new StringBuilder(word);
                currentY -= lineHeight;
                lines++;
            } else {
                currentLine = new StringBuilder(testLine);
            }
        }

        // 绘制最后一行
        if (currentLine.length() > 0) {
            contentStream.beginText();
            contentStream.newLineAtOffset(x, currentY);
            contentStream.showText(currentLine.toString());
            contentStream.endText();
            lines++;
        }

        return lines * lineHeight;
    }
}*/
